package com.tarena.csmall.order.web.service;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.front.dto.ReduceSkuDTO;
import cn.tedu.mall.pojo.order.dto.OrderAddDTO;
import cn.tedu.mall.pojo.order.dto.OrderItemAddDTO;
import cn.tedu.mall.pojo.order.vo.OrderAddVO;
import com.tarena.csmall.front.api.sku.SkuApi;
import com.tarena.csmall.order.web.repository.OrderRepository;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderService {
    @DubboReference
    private SkuApi skuApi;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private CartService cartService;
    @Transactional
    public OrderAddVO orderAdd(OrderAddDTO dto) {
        //1 根据当前订单的信息 到front服务中进行库存的删减
        //减库存参数封装
        List<ReduceSkuDTO> reduceSkus=new ArrayList<>();
        //生成购物车删除的参数之一
        List<Long> skuIds=new ArrayList<>();
        for (OrderItemAddDTO item : dto.getOrderItems()) {
            ReduceSkuDTO reduceSkuDTO=new ReduceSkuDTO();
            reduceSkuDTO.setSkuId(item.getSkuId());
            reduceSkuDTO.setQuantity(item.getQuantity());
            reduceSkuDTO.setOrderSn(dto.getSn());
            reduceSkus.add(reduceSkuDTO);
            skuIds.add(item.getSkuId());
        }
        //多个商品同时减库存,操作多条sql语句,有一条执行失败,反馈给订单方都是false
        Boolean success=false;
        try{
            success=skuApi.reduceStock(reduceSkus);
        }catch (Exception e){
            e.printStackTrace();
            throw new CoolSharkServiceException(ResponseCode.CONFLICT,"某个商品库存不足,请重新下单");
        }
        if (!success){
            throw new CoolSharkServiceException(ResponseCode.CONFLICT,"某个商品库存不足,请重新下单");
        }
        //2 新增订单
        orderRepository.orderAdd(dto);
        //3 删除购物车 userId skuIds
        Long userId=dto.getUserId();
        cartService.deleteOrderCart(userId,skuIds);
        //4 返回的对象
        OrderAddVO orderAddVO=new OrderAddVO();
        orderAddVO.setCreateTime(LocalDateTime.now());
        orderAddVO.setSn(dto.getSn());
        orderAddVO.setPayAmount(dto.getAmountOfActualPay());
        return orderAddVO;
    }
}
